//
//  YWDoMeterReadingTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/20.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoMeterReadingTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UIImage+Extension.h"
#import "NSDate+Additions.h"

#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"

#import "YWMeterReadingDetailRecordCell.h"
#import "YWMeterSelectMonthCell.h"
#import "YWWriteMeterReadingNumberCell.h"
#import "YWTakePhotoCell.h"
#import "YWLocationCell.h"
#import "YWWriteNoteCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

#import "YWCommonTool.h"
#import "YWMeterReadingManager.h"
#import "YWEquipmentManager.h"
#import "YWMeterReadingRecord.h"
#import "YWBuildingManager.h"
#import "YWMeterReadingManager.h"
#import "YWMeterReadingRecord.h"

@interface YWDoMeterReadingTableViewController ()<YWTakePhotoCellDelegate,YWWriteMeterReadingNumberCellDelegate,YWMeterSelectMonthCellDelegate,YWWriteNoteCellDelegate>{
    NSString *selectedMonth;
    NSString *writtingReadingNumber;
    NSString * noteString;
}
@property (nonatomic,strong) NSMutableArray *dateSource;
@property (nonatomic, strong) YWMeterReadingRecord* lastReadingRecord;
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, assign) BOOL isClickFinish;
@end

@implementation YWDoMeterReadingTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finishEvent)];
    
    [self initDate];
    [self inittableViewRegistCell];
    [self requestLastReadingNumber];
}

- (void)initDate{
    self.lastReadingRecord = [[YWMeterReadingManager shareManager] latestMeterReadingRecordWithEquipmentId:self.equipment.equipmentId];
    NSDate* nowDate = [NSDate date];
    if (nowDate.month<10) {
        selectedMonth = [NSString stringWithFormat:@"%ld-0%ld",(long)nowDate.year,(long)nowDate.month];
    }else{
        selectedMonth = [NSString stringWithFormat:@"%ld-%ld",(long)nowDate.year,(long)nowDate.month];
    }
}

- (void)inittableViewRegistCell{
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    [self.tableView registerClass:[YWMeterSelectMonthCell class] forCellReuseIdentifier:YWMeterSelectMonthCellIdentifier];
    [self.tableView registerClass:[YWWriteMeterReadingNumberCell class] forCellReuseIdentifier:YWWriteMeterReadingNumberCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWLocationCell class]forCellReuseIdentifier:YWLocationCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)requestLastReadingNumber{
    YWWeakSelf(weakSelf);
    [[YWMeterReadingManager shareManager] requestNewestReadingMemterRecord:weakSelf.equipment.equipmentId complete:^(YWMeterReadingRecord* record) {
        if (record) {
            weakSelf.lastReadingRecord = record;
            weakSelf.dateSource = nil;
            [weakSelf.tableView reloadData];
        }
        NSString* lastTimeStr = [YWCommonTool showTimeWithNormalFormatter:weakSelf.lastReadingRecord.readingTime / 1000];
        double lastTimeInterval = (double)record.readingTime * 1000;
        long long lastTime = (long long)lastTimeInterval;
        long long nowTime = [YWCommonTool negativeTimestampId];
        ///间隔10分钟
        if (nowTime - lastTime < 10 * 60 * 1000 * 1000) {
            NSString *tips = [NSString stringWithFormat:@"%@已抄过，是否继续抄表", lastTimeStr];
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:tips preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];
}

- (void)setEquipment:(YWEquipment*)equipment
{
    _equipment = equipment;
    NSInteger eEquipmentTypeId = [[YWMeterReadingManager shareManager] electricMeterEquipmentTypeId];
    NSInteger wEquipmentTypeId = [[YWMeterReadingManager shareManager] waterMeterEquipmentTypeId];
    NSInteger gEquipmentTypeId = [[YWMeterReadingManager shareManager] gasMeterEquipmentTypeId];
    if (equipment.equipmentTypeId == wEquipmentTypeId) {
        self.title = @"抄表（水表）";
    }
    else if (equipment.equipmentTypeId == eEquipmentTypeId) {
        self.title = @"抄表（电表）";
    }
    else if (equipment.equipmentTypeId == gEquipmentTypeId) {
        self.title = @"抄表（煤气）";
    }
    else {
        self.title = @"抄表";
    }
}

- (NSMutableArray *)dateSource{
    if (!_dateSource) {
        _dateSource = [NSMutableArray array];
        [_dateSource addObject:[self equipmentName]];
        [_dateSource addObject:[self ownCode]];
        [_dateSource addObject:[self rate]];
        [_dateSource addObject:[self companyName]];
        [_dateSource addObject:[self place]];
        [_dateSource addObject:[self lastReadMeteer]];
        [_dateSource addObject:[self lastMeter]];
        [_dateSource addObject:[self lastReadingMonth]];
    }
    return _dateSource;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return self.dateSource.count;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return UITableViewAutomaticDimension;
//        [tableView fd_heightForCellWithIdentifier:YWLocationCellIdentifier cacheByIndexPath:indexPath configuration:^(YWLocationCell *cell) {
//            [self configureLocationCell:cell atIndexPath:indexPath];
//        }];
    }else if (indexPath.section == 5) {
        CGFloat imageH = YWPhotoSize*(self.equipment.totalImageNameArray.count/4+1) + YWPhotoGap*(self.equipment.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else if (indexPath.section == 3){
        return UITableViewAutomaticDimension;//44;
    }else if(indexPath.section == 2){
        return UITableViewAutomaticDimension;//44;
    }else if(indexPath.section == 4){
        return 90;
    }else{
        return UITableViewAutomaticDimension;//30;
    }
}

- (void)configureLocationCell:(YWLocationCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.locationText = [[YWBuildingManager shareManager] equipmentLocation:self.equipment];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWLocationCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLocationCellIdentifier];
        [self configureLocationCell:cell atIndexPath:indexPath];
        return cell;
        
    }else if (indexPath.section == 1){
        
        YWMeterReadingDetailRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentLabel.text = self.dateSource[indexPath.row];
        return cell;
        
    }else if (indexPath.section == 2){
        
        YWMeterSelectMonthCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterSelectMonthCellIdentifier];
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section == 3){
        
        YWWriteMeterReadingNumberCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteMeterReadingNumberCellIdentifier];
        cell.placeholderStr = @"填写读数(使用量 = 读数*倍率)";
        cell.delegate = self;
        return cell;
        
    }else if(indexPath.section == 4){
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
    }else{
        
        YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.totalImageNameArray = self.equipment.totalImageNameArray;
        cell.delegate = self;
        return cell;
    }
}

- (void)resetCellFrameWithImages:(NSArray*)images cell:(UITableViewCell*)cell
{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    self.equipment.totalImageNameArray = arr;
    [self.tableView reloadData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - button action
- (void)finishEvent{
    _isClickFinish = YES;
    [self handleNextButtonEvent];
//    CGFloat thisReadNumber = [writtingReadingNumber floatValue];
//    if (thisReadNumber>0) {
//        [self handleNextButtonEvent];
//    }else{
//        if (self.enterFromButton) {
//            [self.navigationController popViewControllerAnimated:YES];
//        }else{
//            [self dismissViewControllerAnimated:YES completion:nil];
//        }
//    }
}

- (void)passNote:(NSString*)note
{
    noteString = note;
}

- (void)handleNextButtonEvent{
    //新建模型数据，插入数据库，提交数据，返回数据的id，修改记录的id
    [self.view endEditing:YES];
    NSString* tips = @"确认提交记录";
    CGFloat thisReadNumber = [writtingReadingNumber floatValue];
    NSString *readingMonthStr = [selectedMonth stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSInteger readingMonth = [readingMonthStr integerValue];
    NSString *lastReadingMonthStr = [self.lastReadingRecord.readingMonth stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSInteger lastReadingMonth = [lastReadingMonthStr integerValue];
    if (thisReadNumber<=0) {
        [YWCommonTool showTextHUDWithContent:@"请填写读数"];
        return;
    }
    if ([YWCommonTool isContainsEmoji:noteString]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (readingMonth>=lastReadingMonth && thisReadNumber < self.lastReadingRecord.thisReadNumber) {
        [YWCommonTool showTextHUDWithContent:@"读数不能小于上次读数"];
        return;
    }
    else if (readingMonth<lastReadingMonth && thisReadNumber > self.lastReadingRecord.thisReadNumber){
        [YWCommonTool showTextHUDWithContent:@"读数不能大于上次读数"];
        return;
    }
    //        tips = @"本次读数小于上次读数,是否修改上次读数";
    //        YWAlertView* alert = [[YWAlertView alloc] initWithTitle:@"提示" contentText:tips leftButtonTitle:@"取消" rightButtonTitle:@"去修改"];
    //        [alert show];
    //        alert.leftBlock = ^() {
    //            [self.thisTextField becomeFirstResponder];
    //        };
    //        alert.rightBlock = ^() {
    //            YWMeterReadingRecord* record = [[YWMeterReadingManager shareManager] meterReadingRecordWithRecordId:self.lastReadingRecord.meterRecordId];
    //            if (record) {
    //                YWMeterReadingDetailRecordViewController* detailVC = [[YWMeterReadingDetailRecordViewController alloc] init];
    //                detailVC.meterReadingRecord = record;
    //                [self.navigationController pushViewController:detailVC animated:YES];
    //            }
    //            else {
    //                [YWCommonTool showTextHUDWithContent:@"记录获取失败,请查看记录详情"];
    //            }
    //        };
    
    //    else {
    //完成提交
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:tips preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.HUD.labelText = @"提交记录中";
        [self.HUD show:YES];
        YWMeterReadingRecord* record = [self creatMeterReadingRecord];
        BOOL saveRecord = [[YWMeterReadingManager shareManager] updateMeterReadingRecordWithRecord:record];
        NSArray* pictures = [self createPicturesWithMeterReadingRecord:record];
        BOOL savePicturesToDB = [[YWMeterReadingManager shareManager] updatePatrolPictureWithArray:pictures];
        if (saveRecord && savePicturesToDB && record) {
            [self.HUD hide:YES];
            [[YWMeterReadingManager shareManager] startUploadMeterReadingRecords:@[ record ] pictures:pictures];
            
            [YWCommonTool showTextHUDWithContent:@"提交记录成功"];
            if (_isClickFinish && !self.enterFromButtonOrNoQrcode) {
                //延时是为了不和alertview的动画冲突
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self finishDismissView];
                });
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
            NSDictionary * dic =[[NSDictionary alloc] initWithObjectsAndKeys:self.equipment,@"equipment", nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostMaterReadingSuccessNotification object:nil userInfo:dic];
        }
        else {
            [self.HUD hide:YES];
            YWLog(@"保存数据库失败");
            [YWCommonTool showTextHUDWithContent:@"提交抄表记录失败"];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)finishDismissView{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (YWMeterReadingRecord*)creatMeterReadingRecord
{
    YWMeterReadingRecord* meterReadingRecord = [[YWMeterReadingRecord alloc] init];
    meterReadingRecord.meterRecordId = [NSString stringWithFormat:@"%ld", (long)[YWCommonTool randStringId]];
    meterReadingRecord.equipmentId = self.equipment.equipmentId;
    meterReadingRecord.equipmentTypeId = self.equipment.equipmentTypeId;
    //    meterReadingRecord.lastReadNumber = self.lastReadingRecord.thisReadNumber;
    //    meterReadingRecord.lastReadTime = self.lastReadingRecord.readingTime;
    meterReadingRecord.readingMonth = selectedMonth;
    meterReadingRecord.note = noteString;
    meterReadingRecord.thisReadNumber = [writtingReadingNumber floatValue];
    meterReadingRecord.uploadStatus = YWMeterReadingRecordUploadStatusUploading;
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970] * 1000;
    meterReadingRecord.readingTime = nowTime;
    NSString* yearMonth = [YWCommonTool showTime:nowTime / 1000 andFormatter:KTimeFormatYearMonth];
    yearMonth = [yearMonth stringByReplacingOccurrencesOfString:@"-" withString:@""];
    meterReadingRecord.yearMonth = [yearMonth integerValue];
    NSString* dateShow = [YWCommonTool showTime:nowTime / 1000 andFormatter:KTimeFormatShortDateTime];
    meterReadingRecord.yearMonthDay = [YWCommonTool showTime:nowTime / 1000 andFormatter:KTimeFormatDate];
    meterReadingRecord.dateShow = dateShow;
    meterReadingRecord.uniqueTag = [YWCommonTool randStringId];
    return meterReadingRecord;
}

- (NSArray*)createPicturesWithMeterReadingRecord:(YWMeterReadingRecord*)record
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.equipment.totalImageNameArray count]; i++) {
        YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
        picture.recordId = record.meterRecordId;
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.equipment.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureRecordUploadStatusNull;
        picture.recordType = YWPictureRecordTypeMeterReading;
        [pictures addObject:picture];
    }
    return pictures;
}

- (NSString *)equipmentName{
    NSString *equipmentName = [NSString stringWithFormat:@"设备名称: %@",self.equipment.equipmentName?:@""];
    return equipmentName;
}

- (NSString *)ownCode{
    NSString * ownCode =[NSString stringWithFormat:@"表号: %@", self.equipment.ownCode];
    return ownCode;
}

- (NSString *)rate{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.equipment.equipmentId];
    NSString * rate = [NSString stringWithFormat:@"倍率: %.1f",meterProperty.rate>0?meterProperty.rate:1.0];
    return rate;
}

- (NSString *)companyName{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.equipment.equipmentId];
    NSString * companyName = [NSString stringWithFormat:@"单位名称: %@",meterProperty.companyName.length>0 ? meterProperty.companyName:@"无"];
    return companyName;
}

- (NSString *)place{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.equipment.equipmentId];
    NSString * place = [NSString stringWithFormat:@"房号: %@",meterProperty.place.length>0 ? meterProperty.place:@"无"];
    return place;
}

- (NSString *)lastReadMeteer{
    NSString * lastReadMeteer = [NSString stringWithFormat:@"上次读数: %.2f", self.lastReadingRecord.thisReadNumber];
    return lastReadMeteer;
}

- (NSString *)lastMeter{
    NSString* lastTimeStr = self.lastReadingRecord.readingTime?[YWCommonTool showTimeWithNormalFormatter:self.lastReadingRecord.readingTime / 1000]:@"无";
    NSString * lastMeter = [NSString stringWithFormat:@"上次抄表: %@", lastTimeStr];
    return lastMeter;
}

- (NSString *)lastReadingMonth{
    NSString* readingMonth = self.lastReadingRecord.readingMonth?:@"无";
    NSString * lastReadingMonth = [NSString stringWithFormat:@"上次抄表月份: %@", readingMonth];
    return lastReadingMonth;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+15*2);
        UIButton* nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
        nextButton.frame = CGRectMake(10, 15, SCREEN_WIDTH-10*2, kButtonH);
        [nextButton setBackgroundColor:[UIColor whiteColor]];
        [nextButton setTitle:@"下一个" forState:UIControlStateNormal];
        nextButton.titleLabel.font = kBoldTitleFont;
        [nextButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [nextButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [nextButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        nextButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        nextButton.layer.borderWidth = 1.0;
        nextButton.layer.masksToBounds = YES;
        nextButton.layer.cornerRadius = 5.0;
        
        [nextButton addTarget:self action:@selector(handleNextButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:nextButton];
        _footView = footView;
    }
    return _footView;
}

- (void)transmitTextFieldValue:(NSString *)readingValue cell:(UITableViewCell *)cell{
    writtingReadingNumber = readingValue;
}

- (void)transmitButtonTitle:(NSString *)monthValue cell:(UITableViewCell *)cell{
    selectedMonth = monthValue;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
